<?php
// +----------------------------------------------------------------------
// | QbtCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.qbt8.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 千佰特 <http://www.qbt8.com>
// +----------------------------------------------------------------------
namespace plugins\qbt_alisms\controller;

use think\Controller;
use think\Db;
vendor("sms.SignatureHelper");
class SendSmsController extends Controller
{
    //配置
    private $config;

    function __construct(){
        $info =  Db::name('alisms')->where("id = 1")->find();
        $config = $this->assign("info", json_decode($info['config_json'],true));
        $this->config = $config;
    }

    /**
     * @param $phoneNum 手机号码
     * @param $temp_param 短信模板参数 数组
     * @param $signName 短信签名
     * @param $tempCode 短信模板Code
     * @return mixed
     */
    public function sendSms($phoneNum,$temp_param,$tempCode='') {
        $config = $this->config;
        if ($tempCode==''){
            $tempCode = $config["tempCode"];
        }
        $params = array ();
        // *** 需用户填写部分 ***
        // fixme 必填：是否启用https
        $security = false;
        // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
        $accessKeyId = $config["key"];
        $accessKeySecret = $config["secret"];
        // fixme 必填: 短信接收号码
        $params["PhoneNumbers"] = $phoneNum;
        // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $params["SignName"] = $config["signName"];
        // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = $tempCode;
        // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
        $params['TemplateParam'] = $temp_param;
        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }
        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new \SignatureHelper();
        // 此处可能会抛出异常，注意catch
        $content = $helper->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            )),
            $security
        );
        return $content;
    }
}
